package com.googlecode.allinclusive.fw.web.struts2.interceptor;

import java.text.MessageFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.googlecode.allinclusive.fw.web.valueobject.UserObject;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;

/**
 * 操作日志输出拦截处理
 */
@SuppressWarnings("serial")
public class LoggingInterceptor extends UrlActionInterceptor {
	
	/** log实例*/
	private static final Log log = LogFactory.getLog(LoggingInterceptor.class);
	
	/** 日志格式*/
	private static final MessageFormat messageFormat = new MessageFormat("[session:{0} user:{1}] action:{2}#{3}");
	
	/**
	 * 日志拦截处理
	 */
	protected String doIntercept(ActionInvocation invocation) throws Exception {

		// 输出操作日志
		log(invocation);

		return invocation.invoke();
	}
	
	/**
	 * 输出操作日志
	 * @param invocation Action句柄
	 */
	protected void log(ActionInvocation invocation) {
		ActionContext ac = invocation.getInvocationContext();
		HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);
		// 当前会话
		HttpSession session = request.getSession();
		final String sessionId = session.getId();
		// 当前操作用户
		final UserObject userObject = (UserObject) session.getAttribute(UserObject.USER_OBJECT_KEY);
		final String userId;
		if (userObject != null) {
			userId = userObject.getUserId();
		} else {
			userId = null;
		}
		// 当前处理Action类/方法
		final String actionName = invocation.getAction().getClass().getSimpleName();
		final String methodName = invocation.getProxy().getMethod();

		// 操作日志输出
		log.info(messageFormat.format(new Object[]{sessionId, userId, actionName, methodName}));
	}

}
